package com.pay.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付
 *
 * @author chen
 */
public class AliPayServer {

    private AliConfig aliConfig;

    public AliPayServer(AliConfig aliConfig) {
        this.aliConfig = aliConfig;
    }

    /**
     * 支付宝统一下单
     *
     * @param notifyUrl
     * @param subject
     * @param outTradeNo
     * @param totalAmount
     * @param userId      支付宝的id
     * @return
     * @throws Exception
     */
    public Map<String, Object> aliPay(String notifyUrl, String subject, String outTradeNo, String totalAmount, String userId) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliConfig.appid(), aliConfig.private_key(), "json", "UTF-8", aliConfig.alipay_public_key(), "RSA2");

        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        request.setNotifyUrl(notifyUrl);//设置回调地址
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("out_trade_no", outTradeNo);
        paramMap.put("buyer_id", userId);
        paramMap.put("subject", subject);
        paramMap.put("total_amount", totalAmount);
        String param = JSONObject.toJSONString(paramMap);
        request.setBizContent(param);
        AlipayTradeCreateResponse execute = alipayClient.execute(request);
        if (execute.isSuccess()) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("trade_no", execute.getTradeNo());
            return resultMap;
        } else {
            throw new Exception("创建请求失败");
        }
    }

    /**
     * 支付宝统一下单
     *
     * @param notifyUrl
     * @param subject
     * @param outTradeNo
     * @param totalAmount
     * @param userId      支付宝的id
     * @return
     * @throws Exception
     */
    public Map<String, Object> aliPayPassbackParams(String notifyUrl, String subject, String outTradeNo, String totalAmount, String userId, String passbackParams) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliConfig.appid(), aliConfig.private_key(), "json", "UTF-8", aliConfig.alipay_public_key(), "RSA2");

        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        request.setNotifyUrl(notifyUrl);//设置回调地址
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("out_trade_no", outTradeNo);
        paramMap.put("buyer_id", userId);
        paramMap.put("subject", subject);
        paramMap.put("total_amount", totalAmount);
        paramMap.put("passback_params", passbackParams);
        String param = JSONObject.toJSONString(paramMap);
        request.setBizContent(param);
        AlipayTradeCreateResponse execute = alipayClient.execute(request);
        if (execute.isSuccess()) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("trade_no", execute.getTradeNo());
            return resultMap;
        } else {
            throw new Exception("创建请求失败");
        }
    }

    /**
     * 统一收单线下交易预创建（二维码）
     *
     * @param out_trade_no
     * @param total_amount
     * @param subject
     * @param notifyUrl    回调地址后缀
     * @return
     * @throws Exception
     */
    public Map<String, Object> tradePrecreate(String notifyUrl, String out_trade_no, Double total_amount, String subject) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliConfig.appid(), aliConfig.private_key(), "json", "UTF-8", aliConfig.alipay_public_key(), "RSA2");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(notifyUrl);
        Map<String, Object> param = new HashMap<>();
        param.put("out_trade_no", out_trade_no);
        param.put("total_amount", total_amount);
        param.put("subject", subject);
        request.setBizContent(JSONObject.toJSONString(param));
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        String body = response.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (response.isSuccess()) {
            if (response.getCode().equals("10000")) {
                return jsonObject;
            } else {
                throw new Exception("创建失败" + response.getMsg() + "::" + response.getSubMsg());
            }

        } else {
            throw new Exception("创建请求失败");
        }
    }

    /**
     * 查询支付宝支付情况
     *
     * @param out_trade_no
     * @return
     * @throws AlipayApiException
     */
    public Map<String, Object> tradeQuery(String out_trade_no) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliConfig.appid(), aliConfig.private_key(), "json", "UTF-8", aliConfig.alipay_public_key(), "RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        Map<String, Object> param = new HashMap<>();
        param.put("out_trade_no", out_trade_no);
        request.setBizContent(JSONObject.toJSONString(param));
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            return JSONObject.parseObject(response.getBody());
        } else {
            throw new Exception("查询请求失败");
        }
    }

    /**
     * 支付宝退款
     *
     * @param out_trade_no
     * @param refund_amount
     * @return
     * @throws AlipayApiException
     */
    public Map<String, Object> tradeRefund(String out_trade_no, Double refund_amount, String out_request_no) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", aliConfig.appid(), aliConfig.private_key(), "json", "UTF-8", aliConfig.alipay_public_key(), "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        Map<String, Object> param = new HashMap<>();
        param.put("out_trade_no", out_trade_no);
        param.put("refund_amount", refund_amount);
        param.put("out_request_no", out_request_no);
        request.setBizContent(JSONObject.toJSONString(param));
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        String buyerLogonId = response.getBuyerLogonId();
        String code = response.getCode();
        String msg = response.getMsg();
        String refundSettlementId = response.getRefundSettlementId();
        String s = JSONObject.toJSONString(response);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            return JSONObject.parseObject(response.getBody());
        } else {
            throw new Exception("退款调用失败");
        }
    }
}
